#include <iostream>
#include <cstring>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>

#include "Comman.hpp"

int main()
{
    // 获取关键字
    key_t key = GetKey();
    std::cout << "获取关键字成功, key: "<< key << std::endl;
    sleep(3);

    // 形成共享内存
    int shmid = createshm(key);
    std::cout << "形成共享内存成功, shmid: "<< shmid << std::endl;
    sleep(3);

    // 将地址空间挂接到共享内存中
    char *address = (char *)shmat(shmid, nullptr, 0);
    if (address == (char *)(-1))
    {
        std::cerr << "error " << errno << " strerror: " << strerror(errno) << std::endl;
        exit(3);
    }
    std::cout << "挂接地址空间成功" << std::endl;
    sleep(3);

    while (true)
    {
        if (strcmp(address, "quit") == 0)
        {
            break;
        }
        std::cout << "Client Say: " << address << std::endl;
    }

    //将地址空间从共享内存中去关联
    shmdt(address);
    std::cout << "去关联成功" << std::endl;
    sleep(3);

    //关闭共享内存
    int ctl = shmctl(shmid, IPC_RMID, nullptr);
    if (ctl < 0)
    {
        std::cerr << "error " << errno << " strerror: " << strerror(errno) << std::endl;
        exit(4);
    }
    std::cout << "关闭共享内存成功" << std::endl;
    sleep(3);

    return 0;
}